﻿using System;
using System.Threading;

namespace SingletonPattern
{
    /// <summary>
    /// Auther : Jimmy.you
    /// Desc   : singleton basied on thread safe mode
    /// Date   : 2018-07-19 01:24
    /// </summary>
    public class ThreadSingleton
    {
        /// <summary>
        /// 线程辅助对象
        /// </summary>
        private static readonly object obj = new object();
        private static ThreadSingleton _instance;

        private ThreadSingleton() { }

        public static ThreadSingleton GetInstance()
        {
            lock (obj)
            {
                // print current thread hashcode & start time
                Console.WriteLine("Current thread num is {0}, startTime is {1}", Thread.CurrentThread.GetHashCode(), DateTime.Now);
                if (null == _instance)
                {
                    _instance = new ThreadSingleton();
                }
                // print current thread hashcode & end time & singleton instance hashcode
                Console.WriteLine("Current thread num is {0}, EndTime is {1}, Instance hashcode is {2}"
                    , Thread.CurrentThread.GetHashCode(), DateTime.Now, _instance.GetHashCode());
            }

            return _instance;
        }
    }
}